<script setup lang="ts">
const { t, locale } = useI18n();
const appStore = useAppStore()
import { useForm } from 'vee-validate';
import * as yup from 'yup';
import { Form } from 'vee-validate';
const { brandAmount } = storeToRefs(useBrandStore())
const transfer = useTransferStore()
const brandStore = useBrandStore()
const { isKYCVerifyOpen } = storeToRefs(useBrandStore())
const { isLogin, userInfo, currentGlobalCurrency, balanceData, readyGetUpayBalance, uPayBalance, loadingUpayBalance, loadingUpayUrl, uPayUrl, upayBalErrCode, isCompleteKYC } = storeToRefs(appStore)
const { depositCurrencyList, runGetFinanceDepositCurrencyData, withdrawCurrencyList } = useCurrencyData()
defineOptions({
  name: 'AppLawCurrencyWithdraw',
})


const showSheet = ref(false)
const showBankSheet = ref(false)
const showWithdrawMethodSheet = ref(false)
const selectedCurrency = ref()
const selectedMerchant = ref()
const selectedBank = ref()
const amount = ref()
const router = useRouter()
const selectedMethod = ref()
const isDataLoading = ref(false)
const selectedAmount = ref()
const showAccountSheet = ref(false)
const selectedAccount = ref()
const withdrawFormRef = ref()

/** 最大提款额 */
const {
  data: withdrawBalance,
  runAsync: runWithdrawBalance,
} = useRequest(ApiFinanceWithdrawBalance)

const minWithdraw = computed(() => Number(brandAmount.value ? brandAmount.value[`c${selectedCurrency.value.currency_id}`].w ?? 0 : 0))
const schema = computed(() => yup.object().shape({
  amount: yup.number()
    .transform((value: string) => (!value ? undefined : Number(value)))
    .required(t('recharge_amount_placeholder'))
    .min(minWithdraw.value, t('min_amount', {amount: minWithdraw.value}))
    .max(Number(withdrawBalance.value?.withdraw_balance), t('max_amount', {amount: withdrawBalance.value?.withdraw_balance}))
}))

const { resetForm, setFieldValue, values } = useForm({
  validationSchema: schema,
  initialValues: {
    amount: '',
  }
})

/** 获取取款列表 */
const { runAsync: runAsyncWithdrawMethodList, data: withdrawMethodList } = useRequest(ApiFinanceWithdrawMethodList)
/** 获取已经绑定银行卡和钱包, 支持的取款类型, */
const { runAsync: runAsyncWithdrawBankcard, data: allTypeBankcardData, loading: loadingBankcard } = useRequest(ApiFinanceWithdrawBankcard)
/** 获取取款次数 */
const { runAsync: runAsyncWithdrawFeeInfo } = useRequest(ApiFinanceWithdrawFeeInfo)
/** 发起提款 */
const { runAsync: runWithdraw, loading: withdrawLoading } = useRequest(ApiFinanceWithdraw, {
  onSuccess(data, params) {
    const type = selectedCurrency.value.currency_name
    // openNotify({
    //   icon: `coin-${type.toLocaleLowerCase()}`,
    //   title: t('withdraw_in_process'),
    //   message: () => h(AppMemberNotificationsMessage, {
    //     amount: application.formatNumDecimal(params[0].amount, currencyConfig[type].decimal),
    //     currencyType: type,
    //     keypath: 'withdraw_info_going',
    //   }),
    // })
    appStore.getBalanceData()
  },
})

/** 支持的取款类型(allWithdrawType 添加自定义属性 ) */
const withdrawMethods = computed(() => {
  return allWithdrawType.value.map((w) => {
    return {
      ...w,
      label: w.name,
      value: w.type,
      icon: `/payment/deposit/${w.alias}.webp`,
      cardCount: allTypeBankcardListOptions.value.filter(b => b.type_id === w.id).length,
    }
  })
})

/** 当前取款类型: 银行卡 */
const isBankCardType = computed(() => selectedMethod.value === 1)
/** 当前取款类型: 支付宝 */
const isAlipayType = computed(() => selectedMethod.value === 2)
/** 当前取款类型: 钱包支付 */
const isThreePartyWalletType = computed(() => selectedMethod.value === 3)
/** 最大提款额 */
const maxAmount = computed(() => application.formatNumDecimal(withdrawBalance.value?.withdraw_balance ?? 0, 0, 0))
/** 当前出款方式id */
const withdrawTypeId = computed(() => withdrawMethods.value.find(w => w.type === selectedMethod.value?.type)?.id ?? '')
/** 当前出款方式支持的已绑定的钱包/银行列表 */
const walletOrBankList = computed(() => allMemberBankOrWallet.value.filter(a => a.withdraw_type_id === withdrawTypeId.value))
/** 巴西货币使用pix */
const isPix = computed(() => {
  if (selectedCurrency.value)
    return selectedCurrency.value.currency_id === '702'
  return false
})

/** 所有出款方式支持已经绑定的银行或钱包只取接口b的值 */
const allMemberBankOrWallet = computed(() => {
  const data: any[] = allTypeBankcardData.value?.b || []
  if (data.length > 0) {
    const allWithdrawTypeIds = allWithdrawType.value.map(a => a.id)
    return data.filter(w => allWithdrawTypeIds.includes(w.withdraw_type_id))
      .map((a) => {
        return {
          ...a,
          label: a.bank_name,
          value: `${a.bank_id}`,
          icon: `/webp/bank/${a.bank_id}.webp`,
        }
      })
  }
  return []
})

/** 钱包出款方式,已绑定的钱包统计 */
const memberThreePartyWalletList = computed(() => {
  // 如果取款方式有钱包类型 再统计  因为b没有取款类型ID所以要取重叠值
  const haveThreePartyWallet = allWithdrawType.value.find(a => a.type === 3)
  if (haveThreePartyWallet) {
    return allMemberBankOrWallet.value.filter(a => a.withdraw_type_id === haveThreePartyWallet.id).map((b) => {
      return {
        ...b,
        cardCount: allTypeBankcardListOptions.value.filter(card => card.bank_id === b.bank_id).length,
      }
    })
  }
  return []
})

/** 内嵌模式 upay */
const isEmbed = computed(() => {
  const all = allTypeBankcardData.value?.a
  if (all && all.length && selectedBank.value?.value) {
    const obj = all.filter(a => +a.id === +selectedBank.value?.value)[0]
    return !!(obj && obj.embedded && +obj.embedded === 1)
  }
  return false
})

/** 是否已经绑定 upay 账号 */
const hasBindUpayAccount = computed(() => true)

let upayRefreshTimer: any
function refreshUpayBalance() {
  if (loadingUpayBalance.value || loadingUpayUrl.value)
    return
  if (readyGetUpayBalance.value) {
    clearTimeout(upayRefreshTimer)
    upayRefreshTimer = setTimeout(() => {
      appStore.runGetUpayBalance()
    }, upayBalErrCode.value === '5024' ? 2000 : 0)
  }
  console.log(loadingUpayBalance.value, loadingUpayUrl.value, readyGetUpayBalance.value)
}

function goBuyUpay() {
  if (loadingUpayUrl.value)
    return

  if (readyGetUpayBalance.value && hasBindUpayAccount.value) {
    let newWindow: any
    if (!isMiBrowser())
      newWindow = window.open('', '_blank')
    appStore.runGetUpayUrl().then((uu) => {
      console.log('uPayUrl.value === ', uPayUrl.value, uu)

      if (isMiBrowser()) {
        window.open(uu)
      }
      else {
        if (!newWindow)
          return
        newWindow.location.href = uu ?? ''
      }
    })
  }
  else {
    bindPayment(false)
  }
}

const needDisabledBankIds = computed(() => memberThreePartyWalletList.value.filter(a => a.cardCount >= 3).map(b => b.bank_id))

/** 法币列表 */
const currencyList = computed(() => {
  if (withdrawCurrencyList.value.length) {
    return withdrawCurrencyList.value.filter(a => !application.isVirtualCurrency(a.currency_name)).map((b) => {
      return {
        ...b,
        label: b.currency_name as EnumCurrencyKey,
        value: b.currency_name as EnumCurrencyKey,
      }
    })
  }
  return []
})

watch(walletOrBankList, () => {
  selectedBank.value = walletOrBankList.value?.[0] || ''
})



const amountSelectList = computed(() => {
  return [
    {label: t('min_amount'), value: 0},
    {label: '25%', value: Number(maxAmount.value) * 0.25},
    {label: '50%', value: Number(maxAmount.value) * 0.5},
    {label: t('max_amount'), value: Number(maxAmount.value)},
  ]
})

/** 支持的取款类型 银行卡或者钱包或者支付宝  */
const allWithdrawType = computed(() => allTypeBankcardData.value?.w || [])

function selectCurrency(item: Currency) {
  selectedMerchant.value = ''
  amount.value = ''
  showSheet.value = false
  selectedCurrency.value = item
  getData()
}

watch(withdrawMethods, () => {
  selectedMethod.value = withdrawMethods.value?.[0] || ''
}, { immediate: true })

watch(() => currencyList, () => {
  const currency = currencyList.value.find(item => item.currency_name === currentGlobalCurrency.value)
  currency && selectCurrency(currency)
}, { immediate: true })



/** 所有出款方式支持已经绑定的银行或钱包（包含禁用状态）,需要从接口d键和b键中取重叠的值 */
const allTypeBankcardListOptions = computed(() => {
  if (allTypeBankcardData.value && allTypeBankcardData.value.d) {
    const allMemberBankOrWalletIds = allMemberBankOrWallet.value.map(w => w.bank_id)
    const allWithdrawTypeIds = allWithdrawType.value.map(a => a.id)
    return allTypeBankcardData.value.d.filter((item) => {
      return allWithdrawTypeIds.includes(item.type_id) && allMemberBankOrWalletIds.includes(item.bank_id)
    }).map((a) => {
      return {
        ...a,
        label: a.bank_account,
        value: a.id,
        disabled: a.state === 2,
      }
    })
  }
  return []
})

/** 提款账号列表 */
const accountList = computed(() => {
  console.log(allTypeBankcardListOptions.value, allTypeBankcardData.value)
  if (isAlipayType.value) {
    return allTypeBankcardListOptions.value.filter(a => a.type_id === withdrawTypeId.value && `${a.bank_id}`.includes(selectedBank.value?.bank_id))
  }
  else if (isBankCardType.value && !isPix.value) {
    return allTypeBankcardListOptions.value.filter(a => a.type_id === withdrawTypeId.value && `${a.bank_id}`.includes(selectedBank.value?.bank_id)).map((b) => {
      return {
        ...b,
        label: b.bank_account.replace(/(\d{4})/g, '$1 ').trim(),
      }
    })
  }

  return allTypeBankcardListOptions.value.filter(a => a.type_id === withdrawTypeId.value && `${a.bank_id}`.includes(selectedBank.value?.bank_id))
})

watch(accountList, () => {

  const defaultAccount = accountList.value?.find(item => item.is_default === 1)
  selectedAccount.value = defaultAccount || accountList.value?.[0] || ''
})


// 获取所需要的数据
async function getData() {
  try {
    isDataLoading.value = true
    await Promise.all([
      appStore.runAsyncCnyPayCombo(),
      runWithdrawBalance({ currency_id: selectedCurrency.value.currency_id }),
      runAsyncWithdrawMethodList({ currency_id: selectedCurrency.value.currency_id }),
      runAsyncWithdrawBankcard({ currency_id: selectedCurrency.value.currency_id, withdraw_type: '1' }),
    ])
    // appStore.updateUserInfo()
    // 默认选中第一个出款类型
    // selectedMethod.value = allWithdrawType.value[0]
    // 已绑的银行(钱包)大于0
    if (allMemberBankOrWallet.value.length > 0) {
      // 过滤不可用的出款账户
      const _allActiveBankCardList = allTypeBankcardListOptions.value.filter(a => !a.disabled)

      // 检查是否有默认的卡号
      const defaultBankCard = _allActiveBankCardList.find(a => a.is_default === 1)
      if (defaultBankCard) {
        // setBankNameId(allMemberBankOrWallet.value.find(a => a.bank_id === defaultBankCard.bank_id)!.bank_id.toString())
        // selectedMethod.value = allWithdrawType.value.find(a => a.id === defaultBankCard.type_id)!.type
        // setBankId(defaultBankCard.id, false)
      }
      else {
        // 无默认，选中第一个下面有绑定出款账户(可用状态)的出款方式
        // 统计所有出款方式下面各有多少个出款账户(可用状态)
        const _allTypeArr = allWithdrawType.value.map((a) => {
          return {
            ...a,
            cardCount: _allActiveBankCardList.filter(b => b.type_id === a.id).length,
          }
        })
        // 有绑卡的类型
        const obj1 = _allTypeArr.find(a => a.cardCount > 0)
        if (obj1) {
          // selectedMethod.value = obj1?.type
          // 选中可用卡
          const _bankCard = _allActiveBankCardList.find(a => a.type_id === obj1.id)
          if (_bankCard) {
            // setBankId(_bankCard.id, false)
            // 选中可用卡对应的银行
            // setBankNameId(allMemberBankOrWallet.value.find(a => a.bank_id === _bankCard.bank_id)!.value ?? '')
          }
        }
      }
    }
    isDataLoading.value = false
  }
  catch (error) {
    console.error('获取提款数据出错', error)
  }
  finally {
    isDataLoading.value = false
  }
}

onActivated(async () => {
  appStore.runGetUpayBalance()
  await application.allSettled([getData()])
})
await application.allSettled([getData()])

function selectMethod(item: typeof withdrawMethods){
  selectedMethod.value = item
  showWithdrawMethodSheet.value = false
}

function selectBank(item: typeof walletOrBankList){
  selectedBank.value = item
  showBankSheet.value = false
}

function selectAccount(item: typeof accountList){
  selectedAccount.value = item
  showAccountSheet.value = false
}

function bindPayment(submit = true) {
  showAccountSheet.value = false
  if(!walletOrBankList.value?.length || !submit){
    transfer.setData({
      selectedMethod: selectedMethod.value,
      withdrawMethods: withdrawMethods.value,
      currency_id: selectedCurrency.value.currency_id
    })
    router.push('withdraw/bind-account')
  }
}

// 取款操作
async function withDrawSubmit() {
  const { values } = withdrawFormRef.value
  /** 增加kyc逻辑 */
  if (isLogin.value && isKYCVerifyOpen.value && !isCompleteKYC.value)
    return
    //openKYCDialog()
  runAsyncWithdrawFeeInfo({ currency_id: selectedCurrency.value.currency_id }).then((data): void => {
    if (data.withdraw_setting_count > 0 && data.withdraw_count >= data.withdraw_setting_count && !Local.get(STORAGE_DEPOSIT_COUNT + getCurDate() + data.withdraw_count)?.value) {
      //openPromptDialog(data)
      Local.set(STORAGE_DEPOSIT_COUNT + dayjs().format('YYYYMMDD') + data.withdraw_count, data.withdraw_count)
    }
    else {
      // 打开输入资金密码弹窗
      // const { openDialogPassword } = useDialogPassword()
      runWithdraw({
        currency_id: Number(selectedCurrency.value.currency_id),
        method_id: withdrawMethodList.value ? withdrawMethodList.value[0].id : '',
        amount: amount.value,
        pay_password: values.password,
        bankcard_id: selectedAccount.value.value,
        auth_type: 2,
        auth_code: values.password,
      })
    }
  })
}
function goList () {
  showAccountSheet.value = false;
  transfer.setData({
    type: selectedMethod.value.type,
    type_id: selectedMethod.value.id,
    currency_id: selectedCurrency.value.currency_id
  })
  router.push('withdraw/account-list')
}

</script>

<template>
  
  <div class="m-[1rem] p-[1rem] rounded-[.5rem] bg-bg-black-4 mb-[3.75rem]">
    <Form :validation-schema="schema" @submit="withDrawSubmit" ref="withdrawFormRef">
      <BaseInput required :label="t('withdraw_currency')" name="currency_name" :modelValue="selectedCurrency?.label || ''"  @click="showSheet = true" type="select">
        <template v-slot:left-icon>
          <AppCurrencyIcon class="size-[1.25rem]" :currency-type="getCurrencyConfigByCode(selectedCurrency?.currency_id)?.['name']"/>
        </template>
      </BaseInput>
      <BaseInput required :label="t('withdraw_method')" :placeholder="t('withdraw_method')" name="method" :modelValue="selectedMethod?.label || ''"  @click="showWithdrawMethodSheet = true" type="select" class="mt-[1rem]">
        <template v-slot:left-icon v-if="withdrawMethods?.length && selectedMethod">
          <BaseImage width="1.125rem" height="1.125rem" :url="selectedMethod.icon" is-network/>
        </template>
      </BaseInput>
      <BaseInput required :label="t('bank_name')" name="bank" :modelValue="selectedBank?.label || ''"  @click="walletOrBankList?.length && (showBankSheet = true)" :type="walletOrBankList?.length ? 'select' : 'text'" class="mt-[1rem]" :placeholder="walletOrBankList?.length ? t('choose_bank') : t('bind_withdraw_account_tip')" :disabled="!walletOrBankList?.length">
        <template v-slot:left-icon v-if="walletOrBankList?.length && selectedBank">
          <BaseImage width="1.125rem" height="1.125rem" :url="selectedBank?.icon" is-network/>
        </template>
      </BaseInput>
      <BaseInput required :label="t('bank_account')" name="account" type="select" :modelValue="selectedAccount?.label || ''" class="mt-[1rem]" @click="showAccountSheet = true" v-if="accountList?.length">
      </BaseInput>
      <div v-if="isEmbed" class="flex items-center justify-between mt-[.5rem]">
        <div class="flex items-center text-[14px] gap-[.25rem]">
          <span class="text-text-white-2 text-[.75rem]">{{ t('u_pay_balance') }}</span>
          <div v-if="readyGetUpayBalance" class="text-white flex gap-[.25rem]">
            <AppCurrencyIcon class="size-[1.25rem]" :currency-type="getCurrencyConfigByCode(selectedCurrency?.currency_id)?.['name']"/>
            <span class="text-function-red">{{ Number(uPayBalance?.Balance) || '0.00' }}</span>
          </div>
          <span v-else class="text-tg-text-white">{{ t('get_fail') }}</span>
          <div class="flex cursor-pointer items-center justify-center" @click="refreshUpayBalance">
            <BaseIcon name="uni-refresh" :class="{'animate-spin': loadingUpayBalance || loadingUpayUrl}"/>
          </div>
        </div>
        <BaseButton :loading="loadingUpayUrl"  @click="goBuyUpay" html-type="button" type="secondary" class="w-[5.125rem] h-[1.75rem] text-[.75rem] text-brand rounded-[.25rem]">
          <BaseIcon name="uni-plus" class="!text-brand size-[.75rem]" />
          {{ readyGetUpayBalance && hasBindUpayAccount ? t('buy_u_coin') : t('bind_account') }}
        </BaseButton>
      </div>
      <BaseInput required :label="t('withdraw_amount')" name="amount" type="number" class="mt-[1rem]">
        <template v-slot:label-right>
          <div class="text-text-white-2 font-[700]">{{t('max_withdraw_amount')}} <span class="text-function-red">{{ maxAmount }}</span></div>
        </template>
      </BaseInput>
      <AppWithdrawSelectAmount v-model="selectedAmount" :list="amountSelectList" class="mt-[0.5rem]" v-if="+maxAmount > 0"/>
      <BaseButton :html-type="walletOrBankList.length ? 'submit' : 'button'" class="w-full mt-[1rem] text-[.75rem]" @click="bindPayment">{{ walletOrBankList.length ? t('common_confirm_submit') : t('bind_withdraw_account') }}</BaseButton>
      <BaseSheet
        v-model="showSheet"
        :title="t('recharge_choose_currency')"
        :showSearch="true"
        :filterKey="'label'"
        :items="currencyList"
      >
        <template v-slot="{item} : {item?: Currency}">
          <li
            class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
            :class="[(item?.value === selectedCurrency?.value && 'bg-bg-black-4')]"
            @click="selectCurrency(item!)"
          >
            <div class="flex items-center gap-[.1875rem]">
              <!-- 货币图标 -->
              <AppCurrencyIcon class="size-[1.25rem]" :currency-type="getCurrencyConfigByCode(item!.currency_id)?.['name']" />
              <span class="font-medium text-text-white-1 text-[1rem] ml-[.5rem]">{{ item?.currency_name || item?.label }}</span>
            </div>
            <span class="text-text-white-1 text-[1rem]">{{ item?.amount }}</span>
          </li>
        </template>
      </BaseSheet>
      <BaseSheet
        v-model="showWithdrawMethodSheet"
        :title="t('withdraw_method')"
        :items="withdrawMethods"
      >
        <template v-slot="{ item }">
          <li
            class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
            :class="[(item.value === selectedMethod?.value && 'bg-bg-black-4')]"
            @click="selectMethod(item)"
          >
            <div class="flex items-center gap-[.1875rem]">
              <!-- 货币图标 -->
              <BaseImage width="1.125rem" height="1.125rem" :url="item.icon" is-network/>
              <span class="font-medium text-text-white-1 text-[1rem] ml-[.5rem]">{{ item.currency_name || item.label }}</span>
            </div>
            <div class="size-[1rem] border-[.1875rem] border-brand rounded-[50%]" v-if="item.value === selectedMethod?.value"></div>
          </li>
        </template>
      </BaseSheet>
      <BaseSheet
        v-model="showBankSheet"
        :title="t('choose_bank')"
        :items="walletOrBankList"
      >
        <template v-slot="item:any">
          <li
            class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
            :class="[(item.value === selectedBank?.value && 'bg-bg-black-4')]"
            @click="selectBank(item)"
          >
            <div class="flex items-center gap-[.1875rem]">
              <!-- 货币图标 -->
              <BaseImage width="1.125rem" height="1.125rem" :url="item.icon" is-network/>
              <span class="font-medium text-text-white-1 text-[1rem] ml-[.5rem]">{{ item.currency_name || item.label }}</span>
            </div>
            <div class="size-[1rem] border-[.1875rem] border-brand rounded-[50%]" v-if="item.value === selectedBank?.value"></div>
          </li>
        </template>
      </BaseSheet>
      <BaseSheet
        v-model="showAccountSheet"
        :title="t('choose_account')"
        :items="accountList"
      >
        <template v-slot="{ item, index }">
          <div v-if="index === 0" class="flex justify-between mb-[1.25rem]">
            <BaseButton class="h-[1.75rem] w-[3.875rem] ml-[.875rem] !rounded-[.25rem]" html-type="button" type="secondary" @click="goList()">
              <BaseIcon name="uni-manage" class="text-text-black-10" />
              <span class="text-text-black-10 text-[.75rem] ml-[.25rem]">{{t('common_manage')}}</span>
            </BaseButton>
            <BaseButton class="h-[1.75rem] w-[3.875rem] mr-[.875rem] !rounded-[.25rem]" html-type="button" type="secondary" @click="bindPayment(false)">
              <BaseIcon name="uni-plus" class="text-text-black-10 size-[1rem]" />
              <span class="text-text-black-10 text-[.75rem] ml-[.25rem]">{{t('common_add')}}</span>
            </BaseButton>
          </div>
          <li
            class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
            :class="[(item.value === selectedAccount?.value && 'bg-bg-black-4')]"
            @click="selectAccount(item)"
          >
            <div class="flex items-center gap-[.1875rem]">
              <!-- 货币图标 -->
              <BaseImage width="1.125rem" height="1.125rem" :url="item.icon" is-network/>
              <span class="font-medium text-text-white-1 text-[1rem] ml-[.5rem]">{{ item.currency_name || item.label }}</span>
            </div>
            <div class="size-[1rem] border-[.1875rem] border-brand rounded-[50%]" v-if="item.value === selectedAccount?.value"></div>
          </li>
        </template>
      </BaseSheet>
    </Form>
  </div>

</template>
